import tensorflow as tf

# 创建变量
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35), name="weights")  # 初始为随机值
biases = tf.Variable(tf.zeros([200]), name="biases")  # 初始为常量


w2 = tf.Variable(weights.initialized_value(), name="w2")  # 由另一个变量初始化
w_twice = tf.Variable(weights.initialized_value() * 0.2, name="w_twice")  # 由另一个变量初始化并通过计算所得

# 保存器用于保存变量、加载变量，不传递变量默认操作全部变量
saver1 = tf.train.Saver()

# 初始化全部变量
op_init1 = tf.global_variables_initializer()
sess1 = tf.Session()
print(sess1.run(op_init1))
save_path1 = saver1.save(sess1, "data_variable/sess1.ckpt")  # 保存到文件
print(save_path1)
sess1.close()

# 保存器指定要保存的变量
saver2 = tf.train.Saver([weights, biases])

# 初始化指定变量
op_init2 = tf.variables_initializer([weights, biases])
with tf.Session() as sess2:
    print(sess2.run(op_init2))
    save_path2 = saver2.save(sess2, "data_variable/sess2.ckpt")  # 保存到文件
    print(save_path2)
